<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@include file="../includes/tag.jsp" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=basePath%>">
    
    <title>Wcms内容管理系统</title>
    <script type="text/javascript" src="<%=basePath%>resources/lib/jquery/jquery.js"></script>
    <script type="text/javascript" src="<%=basePath%>resources/lib/webui/buss.ui.core.js"></script>
    <script type="text/javascript" src="<%=basePath%>resources/lib/webui/buss.ui.js"></script>
	<script type="text/javascript" src="<%=basePath%>resources/lib/jqgrid/js/i18n/grid.locale-cn.js"></script>
	<script type="text/javascript" src="<%=basePath%>resources/lib/jqgrid/js/jquery.jqGrid.min.js"></script>
	<script type="text/javascript" src="<%=basePath%>resources/lib/public.js"></script>
	
	<link rel="stylesheet" type="text/css" href="<%=basePath%>resources/lib/styles/themes/buss-ui.css">
	<link rel="stylesheet" type="text/css" href="<%=basePath%>resources/lib/jqgrid/css/jquery-ui.css">
	<link rel="stylesheet" type="text/css" href="<%=basePath%>resources/lib/jqgrid/css/ui.jqgrid.css">
    <link rel="stylesheet" type="text/css" href="<%=basePath%>resources/styles/public.css">
    <link rel="stylesheet" type="text/css" href="<%=basePath%>resources/styles/icon.css">

	<script type="text/javascript">
		$(document).ready(function(){						
			setGridData();
			resize();
			$(window).resize(resize);
			$("#add-btn").button({iconCls:'icon-add',handler:function(){				
				var url = '<%=basePath%>admin/role/addpage.do';
				var addUrl = '<%=basePath%>admin/role/add.do';
				var dlg = syscore.editDialog('新增角色信息',url,'',500,250,addUrl,function(rsData){				
					if(rsData.message.code != '0'){
						 $.alert('提示','保存数据失败!原因:' + rsData.message.mess,300,140,'error');
						 return false;
					 }else{						
	       			 	 $("#tabledata").jqGrid().trigger('reloadGrid');				        			 	
	       			 	 dlg.dialog("destroy");
					 }	
				});
			}});		
			$("#edit-btn").button({iconCls:'icon-edit',handler:function(){
				var selRows = $("#tabledata").jqGrid('getGridParam',"selarrrow");
				if(selRows.length == 0){
					$.alert('提示','你没有选择要修改的数据!',300,140,'info');
					return;
				}
				if(selRows.length > 1){
					$.alert('提示','只能选择一条数据，请重新选择!',300,140,'info');
					return;
				}
				var url = '<%=basePath%>admin/role/editpage.do';
				var editUrl = '<%=basePath%>admin/role/edit.do';
				var dlg = syscore.editDialog('修改角色信息',url,'id='+selRows[0],500,250,editUrl,function(rsData){
					if(rsData.message.code != '0'){
						 $.alert('提示','保存数据失败!原因:' + rsData.message.mess,300,140,'error');
						 return false;
					 }else{
        			 	 $("#tabledata").jqGrid().trigger('reloadGrid');			        			 	
	       			 	 dlg.dialog("destroy");
					 }	
				});				
			}});
			$("#del-btn").button({iconCls:'icon-remove',handler:function(){
				var selRows = $("#tabledata").jqGrid('getGridParam',"selarrrow");
				if(selRows.length == 0){
					$.alert('提示','你没有选择要删除的数据!',300,140,'info');
					return;
				}
				$.confirm('提示','确认要删除选中数据吗?',300,140,function(){
					var str = "";
					for(var i = 0;i < selRows.length;i++){
						if(i < selRows.length - 1){
							str += "ids=" + selRows[i] + "&";
						}else{
							str += "ids=" + selRows[i];
						}
					}
					$.post("<%=basePath%>admin/role/delete.do",str,function(rsData){
						if(rsData.message.code != '0'){
							$.alert('错误','删除角色信息失败!原因:' + rsData.message.mess,300,140,'error');
							return;
						}
						$("#tabledata").jqGrid({page:1}).trigger('reloadGrid');
					},"json");
				});				
			}});
			
			$("#set_users").button({iconCls:'icon-remove',handler:function(){
				var selRows = $("#tabledata").jqGrid('getGridParam',"selarrrow");
				if(selRows.length == 0){
					$.alert('提示','你没有选择要设置用户的角色信息!',300,140,'info');
					return;
				}
				if(selRows.length > 1){
					$.alert('提示','只能选择一条数据，请重新选择!',300,140,'info');
					return;
				}
				var panel = "<div>"+
					"<div class='userContext' style='padding:5px;'>" +
					"<table id='userContext_data'/>"+
					"<div id='userContext_datapage'/>"+
					"</div></div>";
				var dlg = $(panel).dialog({
					modal:true,
					height:408,
					width:600,
					title:'角色对应用户',						
					iconCls:'icon',
					topTools:[
					         {text:'添加用户',type:'button',iconCls:'icon-add',plain:true,handler:function(){
					        	 var selectUrl = "<%=basePath%>admin/user/selectUserPage.do";
					        	 var selUserDlg = $("<div/>").dialog({
					        		 modal:true,
					        		 height:400,
					        		 width:600,
					        		 title:'选择用户',
					        		 iconCls:'icon',
					        		 buttonGap:40,
					        		 buttons:[
					        		          {text:'确定',type:'button',iconCls:'icon-save',handler:function(){
					        		        	  var userIds = "";
					        		        	  var selUsers = selUserDlg.find("#sel_userlist").find("option:selected");
							        				 for(var i = 0;i < selUsers.length;i++){
					     									var userId = $(selUsers[i]).attr("value");
					     									var username = $(selUsers[i]).html();
					     									userIds += "userIds="+userId + "&";
							        				 }
							        				 if(userIds == ""){
							        					 $.alert('提示','请先选择要添加的用户!',300,170,'info');
						        						 return;
							        				 }
							        				 var url = "<%=basePath%>admin/user/updateUsersRole/"+selRows[0] + ".do";
							        				 $.post(url,userIds,function(rs){
							        					 if(rs.message.code != 0){
							        						 $.alert('提示','添加用户信息失败，原因:' + rs.message.mess,300,170,'error');
							        						 return;
							        					 }
							        					 dlg.find("#userContext_data").jqGrid().trigger('reloadGrid');
							        					 selUserDlg.dialog("destroy");
							        					 
							        				 },"json");
					        		          }},
					        		          {text:'取消',type:'button',iconCls:'icon-cancel',handler:function(){
					        		        	  selUserDlg.dialog("destroy");
					        		          }}
					        		        ],
					        		 loadUrl:selectUrl,
					        		 onLoad:function(){
					        			 selUserDlg.find("#add-user").button({
					        				 type:'button',handler:function(){
					        					 selUserDlg.find("#userlist").trigger("dblclick");
					        				 }
					        			 });
					        			 selUserDlg.find("#remove-user").button({
					        				 type:'button',handler:function(){
					        					 selUserDlg.find("#sel_userlist").trigger("dblclick");
					        				 }
					        			 });
					        			 selUserDlg.find("#userlist").dblclick(function(){
	     									var selUsers = selUserDlg.find("#userlist option:selected");
	     									for(var i = 0;i < selUsers.length;i++){
		     									var userId = $(selUsers[i]).attr("value");
		     									if(selUserDlg.find("#sel_userlist option[value='"+userId+"']").length == 0){
		     										selUserDlg.find("#sel_userlist").append(selUsers[i]);
		     									}else{
		     										selUserDlg.find("#sel_userlist option[value='"+userId+"']").attr("selected","selected");
		     										$(selUsers[i]).remove();
		     									}
	     									}
	     								});
					        			 selUserDlg.find("#sel_userlist").dblclick(function(){
					        				 var selUsers = selUserDlg.find("#sel_userlist").find("option:selected");
					        				 for(var i = 0;i < selUsers.length;i++){
			     									var userId = $(selUsers[i]).attr("value");
			     									if(selUserDlg.find("#userlist option[value='"+userId+"']").length == 0){
			     										selUserDlg.find("#userlist").append(selUsers[i]);
			     									}else{
			     										selUserDlg.find("#userlist option[value='"+userId+"']").attr("selected","selected");
			     										$(selUsers[i]).remove();
			     									}
		     								 }					        				 
					        			 });
					        			 var root = [{
					     					id:"0",
					     					name:'组织机构',			
					     					isParent:true,
					     					hasNode:true,
					     					open:true
					     				}];
					        			 selUserDlg.find("#organTree").treeview({
					     					treeNodeKey:'id',
					     					treeNodeParentKey:'parentId',
					     					hasChildKey:'hasNode',
					     					nameCol:'name',
					     					nodesCol:'nodes',
					     					expandSpeed:"",
					     					asyncParam:['parentId'],
					     					async:true,
					     					root:{isRoot:true,nodes:root},
					     					asyncUrl:"<%=basePath%>admin/organization/listByTree/0.do",
					     					callback:{
					     						beforeAsyncSuccess:function(msg){
					     							if(msg.message.code == '-2'){
					     								$.alert('提示','你还没有登录或Session已经过期，请重新登录系统!',300,170,'info');
					     								return false;
					     							}
					     							if(msg.message.code == "-1"){
					     								$.alert("提示","获取信息失败，原因：" + msg.message.mess,300,170,'error');
					     								return false;
					     							}
					     							return true;
					     						},
					     						click:function(event,treeId,treeNode){
					     							var url = "<%=basePath%>admin/user/list/" + treeNode.id + ".do";
					     							$.post(url,"disabled=false",function(rs){
					     								
					     								if(rs.message.code != 0){
					     									$.alert("提示","获取信息失败，原因：" + rs.message.mess,300,170,'error');
					     									return false;
					     								}
					     								
					     								var userlist = selUserDlg.find("#userlist");
					     								userlist.html("");
					     								for(var i = 0;i < rs.result.data.length;i++){
					     									var li = $("<option value='"+rs.result.data[i].id+"'>"+rs.result.data[i].userName+"</option>");
					     									userlist.append(li);
					     								}
					     								
					     							},"json");					     							
					     						}
					     					}
					     				});
					        			 
					        		 }
					        	 });
					        	 selUserDlg.dialog("loadPage");
					        	 
					         }},
					         {text:'取消用户',type:'button',iconCls:'icon-remove',plain:true,handler:function(){
					        	 var users = dlg.find("#userContext_data").jqGrid('getGridParam',"selarrrow");
									if(users.length == 0){
										$.alert('提示','你没有选择要取消的用户信息!',300,140,'info');
										return;
									}
									var userIds = "";
									for(var i = 0;i < users.length;i++){
										userIds += "userIds=" + users[i] + "&";
									}
									var url = "<%=basePath%>admin/user/removeUsersRole/" + selRows[0] + ".do";
									$.post(url,userIds,function(rs){
										if(rs.message.code != 0){
											$.alert('提示','取消用户失败，原因：' + rs.message.mess,300,170,'error');
											return;
										}
										dlg.find("#userContext_data").jqGrid().trigger('reloadGrid');
									},"json");
					         }},
							 {text:'关  闭',type:'button',iconCls:'icon-cancel',plain:true,handler:function(){
					        	 dlg.dialog("destroy");
					         }}
					    ]					
				});
			/*	dlg.find("#sel_user").button({iconCls:'icon-search',handler:function(){
					
				}});
				dlg.find("#del_user").button({iconCls:'icon-remove',handler:function(){
					
				}});*/
				var url="<%=basePath%>admin/user/listByRoleId/" + selRows[0] + ".do";
				var colNames = ['用户编码','用户名称','联系电话','移动电话'];
				var colModel = [
							{name:'userId',index:'userId', width:60, sortable:false,align:'left'},
							{name:'userName',index:'userName', width:100,align:'left'},
							{name:'telephone',index:'telephone', width:60,align:'left',sortable:false},
							{name:'mobilePhone',index:'mobilePhone', width:60,align:'left',sortable:false}
						];
				dlg.find("#userContext_data").jqGrid({
					url:url,
					datatype:'json',
					height:285,
					multiselect: true,
					multiboxonly:true,
					autowidth:true,
					autoencode:true,
					viewrecords:true,
					forceFit:true,
					gridview:true,
					loadui:'block',
					rowNum:20,
					sortorder:'asc',
					rownumbers:true,
					colNames:colNames,
					colModel:colModel,
					jsonReader:{
						id:'id',
						root:'result.data',
						page:'result.page.curPageNo',
						total:'result.page.totalPage',
						repeatitems:false
					},
					prmNames:{
						page:'curPageNo',
						rows:'pageSize',
						sort:'orderField',
						order:'orderType'					
					},
					page:1,
					pagerpos:'left',
					pager:dlg.find("#userContext_datapage")
				});
				
			}});
			
			$("#set_permis").button({iconCls:'icon-remove',handler:function(){
				///role/permis/
				var selRows = $("#tabledata").jqGrid('getGridParam',"selarrrow");
				if(selRows.length == 0){
					$.alert('提示','你没有选择要设置权限的角色信息!',300,140,'info');
					return;
				}
				if(selRows.length > 1){
					$.alert('提示','只能选择一条数据，请重新选择!',300,140,'info');
					return;
				}
				var url = "<%=basePath%>admin/role/permis/" + selRows[0] + ".do";
				var dlg = $("<div/>").dialog({
					modal:true,
					header:true,
					height:395,
					width:600,
					title:'角色权限设置',
					iconCls:'icon',
					loadUrl:url,
					buttons:[
					   {text:'确  定',id:'permis_ok',type:'button',iconCls:'icon-save',handler:function(){
						   var tag = $(".tabul .selected").attr("href");
						   tag = tag.substring(tag.lastIndexOf("#"));
						   if(tag == "#menu_permis"){
							   var checkNodes = dlg.find("#menu_tree").treeview("getCheckedNodes",true);
							   //var sysmenus = new Array();
							   var params = "roleId=" + selRows[0] + "&";
							   for(var i = 0;i < checkNodes.length;i++){
								   //sysmenus[i] = checkNodes[i].id;
								   params += "menuIds=" + checkNodes[i].id + "&";
							   }					
							   
							   $.post("<%=basePath%>admin/role/updateRoleMenu.do",params,function(rsData){
									if(rsData.message.code != '0'){
										$.alert('错误','设置角色权限信息失败!原因:' + rsData.message.mess,300,140,'error');
										return;
									}else{
										$.alert('提示','设置角色菜单权限信息成功!',300,140,'success');
									}
								},"json");
						   }
					   }},
					   {text:'关  闭',type:'button',iconCls:'icon-cancel',handler:function(){
						   dlg.dialog("destroy");
					   }}
					],
					onLoad:function(){
						dlg.find("#permis-tabs ul").idTabs("menu_permis");		
						var tag = $(".tabul .selected").attr("href");
						if(tag == "#branch_permis"){
							$("#permis_ok").button("disable");
						}else{
							$("#permis_ok").button("enable");
						}
						dlg.find("#permis-tabs a").click(function(){
							var tag = $(".tabul .selected").attr("href");
							if(tag == "#branch_permis"){
								$("#permis_ok").button("disable");
							}else{
								$("#permis_ok").button("enable");
							}
						});
						loadMenuTree(dlg,selRows[0]);
						dlg.find("#branch-add-btn").button({text:'添加店铺',type:'button',iconCls:'icon-add',plain:true,handler:function(){
							var panel = "<div><div style='margin:5px;'><table id='sel_branch_tabledata'/>" + 
							            "<div id='sel_branch_tablepage'/></div></div>";
							var selDlg = $(panel).dialog({
								modal:true,
								header:true,
								height:395,
								width:600,
								title:"选择店铺信息",
								iconCls:'icon',
								buttons:[
								         {text:'确  定',type:'button',iconCls:'icon-save',handler:function(){
								        	 var selBranchIds = $("#sel_branch_tabledata").jqGrid('getGridParam',"selarrrow");
												if(selBranchIds.length == 0){
													$.alert('提示','你没有选择要设置权限的店铺信息!',300,140,'info');
													return;
												}
												var str = "";
												for(var i = 0;i < selBranchIds.length;i++){
													if(i < selBranchIds.length - 1){
														str += "branchIds=" + selBranchIds[i] + "&";
													}else{
														str += "branchIds=" + selBranchIds[i];
													}
												}
												$.post("<%=basePath%>admin/branch/savebranchrole/"+selRows[0]+".do",str,function(rsData){
													if(rsData.message.code != '0'){
														$.alert('错误','设置店铺权限失败!原因:' + rsData.message.mess,300,140,'error');
														return;
													}
													dlg.find("#branch_tabledata").jqGrid().trigger("reloadGrid");
													selDlg.dialog("destroy");
												},"json");
												
								         }},
								         {text:'取 消',type:'button',iconCls:'icon-cancel',handler:function(){									        	 
								        	 selDlg.dialog("destroy");
								         }}
								        ]
							});
							selectBranchData(selDlg);
						}});
						dlg.find("#branch-remove-btn").button({text:'取消店铺',type:'button',iconCls:'icon-remove',plain:true,handler:function(){
							var selBranchIds = $("#branch_tabledata").jqGrid('getGridParam',"selarrrow");
							if(selBranchIds.length == 0){
								$.alert('提示','你没有选择要取消权限的店铺信息!',300,140,'info');
								return;
							}
							var str = "";
							for(var i = 0;i < selBranchIds.length;i++){
								if(i < selBranchIds.length - 1){
									str += "branchIds=" + selBranchIds[i] + "&";
								}else{
									str += "branchIds=" + selBranchIds[i];
								}
							}
							$.post("<%=basePath%>admin/branch/cancelbranchrole/"+selRows[0]+".do",str,function(rsData){
								if(rsData.message.code != '0'){
									$.alert('错误','取消店铺权限失败!原因:' + rsData.message.mess,300,140,'error');
									return;
								}
								dlg.find("#branch_tabledata").jqGrid().trigger("reloadGrid");								
							},"json");
						}});
						setBranchGridData(selRows[0],dlg);
					}
				});
				dlg.dialog("loadPage");
			}});
		});
		
		function selectBranchData(selDlg){
    		var url = "<%=basePath%>admin/branch/list.do?status=normal";
    		var colNames = ["店铺名称","联系人","联系电话","当前状态"];
    		var colModel = [
    		                {name:'name',index:'name',width:150,align:'left'},
    		                {name:'contact',index:'contact',width:100,align:'left'},
    		                {name:'contactNumber',index:'contactNumber',width:100,align:'left'},
    		                {name:'status',index:'status',width:60,align:'center',formatter:syscore.formaterStatus}
    		               ];
    		syscore.setGridData(selDlg.find("#sel_branch_tabledata"),selDlg.find("#sel_branch_tablepage"),url,colNames,colModel,true,305,'id');
    	};
		
		function setBranchGridData(roleId,dlg){
    		var url = "<%=basePath%>admin/branch/listbranchbyrole/" + roleId + ".do";
    		var colNames = ["店铺名称","联系人","联系电话","当前状态"];
    		var colModel = [
    		                {name:'name',index:'name',width:200,align:'left'},
    		                {name:'contact',index:'contact',width:100,align:'left'},
    		                {name:'contactNumber',index:'contactNumber',width:150,align:'left'},
    		                {name:'status',index:'status',width:60,align:'center',formatter:syscore.formaterStatus}
    		               ];
    		syscore.setGridData(dlg.find("#branch_tabledata"),dlg.find("#branch_tablepage"),url,colNames,colModel,true,238,'id');
    		dlg.find("#branch_tabledata").jqGrid("setGridWidth",568);
    	};
		
		
		function loadMenuTree(dlg,roleId){
			dlg.find("#menu_tree").treeview({
				treeNodeKey:'id',
				treeNodeParentKey:'parentId',
				hasChildKey:'hasNode',
				nameCol:'name',
				checkable:true,
				nodesCol:'nodes',
				expandSpeed:"",
				asyncParam:['parentId'],
				async:true,
				//root:{isRoot:false,nodes:root},
				asyncUrl:function(treeNode){

					return "<%=basePath%>admin/sysmenu/listMenuByRoles/-1.do?roleId=" + roleId;

				},
				callback:{
					beforeAsyncSuccess:function(msg){
						if(msg.message.code == '-2'){
							$.alert('提示','你还没有登录或Session已经过期，请重新登录系统!',300,170,'info');
							return false;
						}
						if(msg.message.code == "-1"){
							$.alert("提示","获取信息失败，原因：" + msg.message.mess,300,170,'error');
							return false;
						}
						var nonCheckedNodes = dlg.find("#menu_tree").treeview("getCheckedNodes",false);
						if(nonCheckedNodes.length == 1 && nonCheckedNodes[0].id=='0'){
							root.checked = true;
							dlg.find("#menu_tree").treeview("updateNode",root,true);
						}
						return true;
					},
					click:function(event,treeId,treeNode){
						//var url = $("#tabledata").jqGrid("getGridParam","url");
						//alert(url);
						//$("#tabledata").jqGrid("setGridParam",{"url":"<%=basePath%>admin/sysmenu/list/" + treeNode.id + ".do"}).trigger('reloadGrid');
						//alert(treeNode.id);
					}
				}
			});
		}
		
		function setGridData(){
			var url = "<%=basePath%>admin/role/list.do";
			var colNames = ['id','角色名称','角色简介'];
			var colModel = [
							{name:'id',index:'id', width:60, hidden:true},
						    {name:'name',index:'name', width:100,align:'left'},
							{name:'remark',index:'remark', width:300,align:'left'}
						];
			syscore.setGridData("#tabledata","",url,colNames,colModel,true);
		}	
		function resize(){
			var h = $(window).height() - $(".nav_curloc").outerHeight() - $(".nav_search").outerHeight() - $(".nav_btn_bar").outerHeight() - 10;
			$(".context").height(h);
			$("#tabledata").jqGrid("setGridHeight",h - 25);
			$("#tabledata").jqGrid("setGridWidth",$(window).width() - 12);
		}
		
	</script>
  </head>
  
  <body>
  	<div style="height:100%;">
  		<div class="nav_curloc">
	    	<label>您的当前位置：<bstag:navbar menuId="${menuid}"/></label>
	    </div>
	  <!--   <div class="nav_search" style="height:28px;">
	    	<table height="100%" cellpadding="0" cellspacing="0">
	    		<tr>
	    			<td valign="middle"">菜单名称：</td>
	    			<td valign="middle"">
	    				<input type="text" size="25" maxlength="100" class="text" name="menu_name"/>
	    			</td>
	    			<td style="padding-left:5px;">
	    				<a id="search-btn" href="javascript:void(0);">查 询</a>
	    			</td>
	    		</tr>
	    	</table>
	    </div> -->
	    <div class="nav_btn_bar">
	    	<table height="100%" cellpadding="0" cellspacing="0">
	    		<tr>
	    			<td valign="middle">
	    				<a id="add-btn" href="javascript:void(0);">新 增</a>
	    			</td>
	    			<td valign="middle"" style="padding-left:5px;">
	    				<a id="edit-btn" href="javascript:void(0);">修 改</a>
	    			</td>
	    			<td valign="middle" style="padding-left:5px;">
	    				<a id="del-btn" href="javascript:void(0);">删 除</a>
	    			</td>
	    			<td valign="middle" style="padding-left:5px;">
	    				<a id="set_permis" href="javascript:void(0);">设置权限</a>
	    			</td>
	    			<td valign="middle" style="padding-left:5px;">
	    				<a id="set_users" href="javascript:void(0);">设置用户</a>
	    			</td>
	    		</tr>
	    	</table>
	    </div>
	    <div class="context">
	    	<table id="tabledata"></table>
	    	<div id="tablepage"></div>
	    </div>
  	</div> 
    
  </body>
</html>
